// 灰度发布监控路由

const express = require('express');
const router = express.Router();
const { grayReleaseManager } = require('../middleware/grayRelease');
const { abTestManager } = require('../utils/abTesting');
const { logger } = require('../../../config/monitoring');

// 获取灰度发布状态
router.get('/status', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const stats = await grayReleaseManager.getGrayReleaseStats();
    const activeExperiments = abTestManager.getActiveExperiments();

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: {
        grayRelease: stats,
        abTests: activeExperiments,
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    logger.error('Failed to get gray release status:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取灰度发布状态失败'
    });
  }
});

// 获取灰度用户列表
router.get('/users', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { page = 1, limit = 20, search } = req.query;

    // 构建查询条件
    const where = { isGrayUser: true };
    if (search) {
      where.$or = [
        { nickname: { $like: `%${search}%` } },
        { phone: { $like: `%${search}%` } }
      ];
    }

    // 查询灰度用户
    // const users = await User.findAndCountAll({
    //   where,
    //   attributes: ['id', 'nickname', 'phone', 'createdAt', 'lastLoginAt'],
    //   limit: parseInt(limit),
    //   offset: (parseInt(page) - 1) * parseInt(limit),
    //   order: [['createdAt', 'DESC']]
    // });

    // 模拟数据
    const users = {
      count: 0,
      rows: []
    };

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: {
        list: users.rows,
        total: users.count,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });

  } catch (error) {
    logger.error('Failed to get gray users:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取灰度用户列表失败'
    });
  }
});

// 添加灰度用户
router.post('/users', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { userIds, phones } = req.body;

    if (!userIds && !phones) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '请提供用户ID或手机号'
      });
    }

    let addedCount = 0;

    // 通过用户ID添加
    if (userIds && userIds.length > 0) {
      // await User.update(
      //   { isGrayUser: true },
      //   { where: { id: { $in: userIds } } }
      // );
      addedCount += userIds.length;
    }

    // 通过手机号添加
    if (phones && phones.length > 0) {
      // await User.update(
      //   { isGrayUser: true },
      //   { where: { phone: { $in: phones } } }
      // );
      addedCount += phones.length;
    }

    logger.info('Gray users added', { 
      addedBy: req.user.id, 
      userIds, 
      phones, 
      count: addedCount 
    });

    res.json({
      success: true,
      code: 200,
      message: `成功添加 ${addedCount} 个灰度用户`
    });

  } catch (error) {
    logger.error('Failed to add gray users:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '添加灰度用户失败'
    });
  }
});

// 移除灰度用户
router.delete('/users', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { userIds } = req.body;

    if (!userIds || userIds.length === 0) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '请提供用户ID'
      });
    }

    // 移除灰度用户标记
    // await User.update(
    //   { isGrayUser: false },
    //   { where: { id: { $in: userIds } } }
    // );

    logger.info('Gray users removed', { 
      removedBy: req.user.id, 
      userIds, 
      count: userIds.length 
    });

    res.json({
      success: true,
      code: 200,
      message: `成功移除 ${userIds.length} 个灰度用户`
    });

  } catch (error) {
    logger.error('Failed to remove gray users:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '移除灰度用户失败'
    });
  }
});

// 获取灰度发布指标
router.get('/metrics', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { startDate, endDate, metric } = req.query;

    // 构建时间范围
    const dateRange = {};
    if (startDate && endDate) {
      dateRange.createdAt = {
        $between: [new Date(startDate), new Date(endDate)]
      };
    }

    // 查询指标数据
    const metrics = {
      userMetrics: {
        totalUsers: 0,
        grayUsers: 0,
        newRegistrations: 0,
        activeUsers: 0,
        retention: {
          day1: 0,
          day7: 0,
          day30: 0
        }
      },
      
      businessMetrics: {
        adViews: 0,
        pointsEarned: 0,
        pointsSpent: 0,
        orders: 0,
        revenue: 0
      },
      
      performanceMetrics: {
        avgResponseTime: 0,
        errorRate: 0,
        crashRate: 0,
        loadTime: 0
      },
      
      feedbackMetrics: {
        totalFeedback: 0,
        bugReports: 0,
        suggestions: 0,
        avgRating: 0
      }
    };

    // 对比数据（灰度用户 vs 非灰度用户）
    const comparison = {
      grayUsers: { ...metrics },
      normalUsers: { ...metrics }
    };

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: {
        overall: metrics,
        comparison,
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    logger.error('Failed to get gray release metrics:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取灰度发布指标失败'
    });
  }
});

// 获取A/B测试结果
router.get('/experiments/:id/results', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { id } = req.params;
    const results = await abTestManager.getExperimentResults(id);

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: results
    });

  } catch (error) {
    logger.error('Failed to get experiment results:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取实验结果失败'
    });
  }
});

// 停止A/B测试
router.post('/experiments/:id/stop', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { id } = req.params;
    const { reason } = req.body;

    await abTestManager.stopExperiment(id, reason);

    logger.info('AB test experiment stopped by admin', { 
      experimentId: id, 
      stoppedBy: req.user.id, 
      reason 
    });

    res.json({
      success: true,
      code: 200,
      message: '实验已停止'
    });

  } catch (error) {
    logger.error('Failed to stop experiment:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '停止实验失败'
    });
  }
});

// 生成灰度发布报告
router.get('/report', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { startDate, endDate, format = 'json' } = req.query;

    // 生成报告数据
    const report = {
      period: {
        startDate: startDate || new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
        endDate: endDate || new Date().toISOString()
      },
      
      summary: {
        totalGrayUsers: 0,
        newGrayUsers: 0,
        activeGrayUsers: 0,
        feedbackCount: 0,
        bugReports: 0,
        avgRating: 0
      },
      
      metrics: {
        performance: {
          avgResponseTime: 0,
          errorRate: 0,
          crashRate: 0
        },
        
        business: {
          adCompletionRate: 0,
          pointsEarned: 0,
          conversionRate: 0
        },
        
        user: {
          retention: 0,
          engagement: 0,
          satisfaction: 0
        }
      },
      
      experiments: [],
      
      recommendations: [
        '继续监控用户反馈',
        '关注性能指标变化',
        '准备全量发布计划'
      ]
    };

    if (format === 'pdf') {
      // 生成PDF报告
      // const pdfBuffer = await generatePDFReport(report);
      // res.setHeader('Content-Type', 'application/pdf');
      // res.setHeader('Content-Disposition', 'attachment; filename=gray-release-report.pdf');
      // res.send(pdfBuffer);
      
      res.status(501).json({
        success: false,
        code: 501,
        message: 'PDF报告生成功能暂未实现'
      });
    } else {
      res.json({
        success: true,
        code: 200,
        message: '获取成功',
        data: report
      });
    }

  } catch (error) {
    logger.error('Failed to generate gray release report:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '生成灰度发布报告失败'
    });
  }
});

module.exports = router;